﻿using System.Collections.Generic;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Media;
using RebEngine.Interfaces;
using RebEngine.Sound;

namespace RebEngine.Managers
{
    public class MusicManager : GameComponent
    {
        private static Dictionary<string, IRebMusic> _songList = new Dictionary<string, IRebMusic>();
        private static bool _initialized = false;
        private static int _songsLoaded = 0;

        public static bool Initialized
        {
            get { return _initialized; }
        }

        public MusicManager(Game game)
            : base(game)
        {

        }

        public static void AddSong(string soundName)
        {
            RebMusic newSong = new RebMusic(soundName);
            if (soundName != null && !_songList.ContainsKey(soundName))
            {

                _songList.Add(soundName, newSong);
                if (_initialized)
                {
                    ThreadStart threadStarter = delegate
                    {
                        newSong.LoadContent();
                    };
                    Thread loadingThread = new Thread(threadStarter);
                    loadingThread.Start();
                }
            LogManager.Write("Song Loaded: " + soundName);
            }
            
        }

        public static void RemoveSong(string soundName)
        {
            if (soundName != null && _songList.ContainsKey(soundName))
            {
                if (_initialized)
                {
                    ThreadStart threadStarter = delegate
                    {
                        _songList[soundName].UnloadContent();
                        _songList.Remove(soundName);
                        _songsLoaded--;
                    };
                    Thread loadingThread = new Thread(threadStarter);
                    loadingThread.Start();
                    LogManager.Write("Song Deleted: " + soundName);
                }
            }
        }

        public static void PlaySong(string soundName)
        {
            if (MediaPlayer.State == MediaState.Stopped)
            {
                MediaPlayer.Play(_songList[soundName].BaseSong);
                LogManager.Write("Playing Song: " + soundName);
            }
        }

        public override void Initialize()
        {
            base.Initialize();

            foreach (IRebMusic sound in _songList.Values)
            {
                if (!sound.ReadyToPlay)
                {
                    sound.LoadContent();
                    _songsLoaded++;
                }
            }
            _initialized = true;
        }
    }
}
